<?php
!defined('IN_SYSTEM') && exit('Access Denied!');

class upload {

	var $dir;			 //附件存放的绝对路径
	var $path;			 //附件存放的相对路径
	var $time;			 //自定义文件上传时间
	var $allow_types;	 //允许上传附件类型
	var $field;			 //上传控件名称
	var $maxsize;		 //最大允许文件大小，单位为KB
	var $filetotal;		 //最大空间，单位为B

	var $thumb_width;    //缩略图宽度
	var $thumb_height;   //缩略图高度

	var $max_width;		//图片最大宽度
	var $max_height;	//图片最大高度

	var $watermark_file; //水印图片地址
	var $watermark_pos;  //水印位置
	var $watermark_trans;//水印透明度


	//构造函数
	//$types : 允许上传的文件类型 , $maxsize : 允许大小 ,  $field : 上传控件名称 , $time : 自定义上传时间
	function upload($types = 'jpg|png', $maxsize = 1024, $field = 'attach', $time = '',$filetotal=0) {
		$this->allow_types = explode('|',strtolower($types));
		$this->maxsize = $maxsize * 1024;
		$this->field = $field;
		$this->time = $time ? $time : TIMESTAMP;
		$this->filetotal = intval($filetotal);
	}

	//设置并创建文件具体存放的目录
	//$basedir  : 基目录，必须为物理路径
	//$filedir  : 自定义子目录，可用参数{y}、{m}、{d}
	function set_dir($basedir,$filedir = '') {
		$dir = $basedir;
		!is_dir($dir) && @mkdir($dir,0777);
		if (!empty($filedir)) {
			$filedir = str_replace(array('{y}','{m}','{d}','\\'),array(gdate('Y',$this->time),gdate('m',$this->time),gdate('d',$this->time),'/'),strtolower($filedir));
			$dirs = explode('/',$filedir);
			foreach ($dirs as $d) {
				!empty($d) && $dir .= $d.'/';
				if ( !is_dir($dir) ) {
					@mkdir($dir,0777);
					@fopen($dir.'index.html','wb');
				}
			}
		}
		$this->dir = $dir;
		$this->path = substr($dir,strlen(BASE_ROOT));
	}

	//图片缩略图设置，如果不生成缩略图则不用设置
	//$width : 缩略图宽度 , $height : 缩略图高度
	function set_thumb ($width = 0, $height = 0) {
		$this->thumb_width  = $width;
		$this->thumb_height = $height;
	}

	//设置自动缩放大小
	function set_resize($width = 0, $height = 0) {
		$this->max_width = $width;
		$this->max_height = $height;
	}

	//图片水印设置，如果不生成添加水印则不用设置
	//$file : 水印图片 , $pos : 水印位置 , $trans : 水印透明度
	function set_watermark ($file, $pos = 6, $trans = 80) {
		$this->watermark_file  = $file;
		$this->watermark_pos   = $pos;
		$this->watermark_trans = $trans;
	}

	/*----------------------------------------------------------------
	执行文件上传，处理完返回一个包含上传成功或失败的文件信息数组，
	其中：ogname	本地的文件名
		  name  为上传后自动生成的文件名，上传失败不存在该值
	      path  为附件的存放路径，不包括文件名，上传失败不存在该值
		  size  为附件大小，上传失败不存在该值
		  type  为附件的MIME类型
		  status  为状态标识，1表示成功，-1表示文件类型不允许，-2表示文件大小超出
	-----------------------------------------------------------------*/
	function execute() {
		$files = array(); //成功上传的文件信息
		if (!count($_FILES)) return false;
		$field = $this->field;
		$keys = array_keys($_FILES[$field]['name']);
		foreach ($keys as $key) {
			if (!$_FILES[$field]['name'][$key]) continue;
			$fileext = strtolower( $this->fileext($_FILES[$field]['name'][$key]) ); //获取文件扩展名
			$filename = gdate('dHis',$this->time).mt_rand(0,99).'.'.$fileext; //生成文件名
			$filesize = $_FILES[$field]['size'][$key]; //文件大小
			//限制上传格式
			$disarr = array('asa','asax','ascx','asxh','asmx','asp','aspx','axd','cer','cs','java','php','php3','php4','shtm','shtml');
			//文件类型不允许
			if (in_array($fileext, $disarr) || !in_array($fileext,$this->allow_types)) {
				$files[$key]['ogname'] = $_FILES[$field]['name'][$key];
				$files[$key]['status'] = -1;
				continue;
			}
			//文件大小超出
			if ($filesize > $this->maxsize) {
				$files[$key]['ogname'] = $_FILES[$field]['name'][$key];
				$files[$key]['status'] = -2;
				continue;
			}
			if ($this->filetotal >0 && ( $filesize + $totalsize > $this->filetotal ) ){
				$files[$key]['ogname'] = $_FILES[$field]['name'][$key];
				$files[$key]['status'] = -3;
				continue;
			}
			$totalsize += $filesize;
			$files[$key]['ogname'] = trim(htmlspecialchars($_FILES[$field]['name'][$key]));
			$files[$key]['name'] = $filename;
			$files[$key]['path'] = $this->path;
			$files[$key]['size'] = $filesize;
			$files[$key]['type'] = $_FILES[$field]['type'][$key];
			$files[$key]['ext'] = $fileext;
			//修正addslashes后win下路径多出转义导致文件无法上传的问题
			$_FILES[$field]['tmp_name'][$key] = str_replace('\\\\','\\',$_FILES[$field]['tmp_name'][$key]);
			//保存上传文件并删除临时文件
			if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {
				move_uploaded_file($_FILES[$field]['tmp_name'][$key],$this->dir.$filename);
				@unlink($_FILES[$field]['tmp_name'][$key]);

				$files[$key]['status'] = 1;

				//对图片进行加水印和生成缩略图
				if (in_array($fileext,array('jpg','png','jpeg'))) {

					if ( $this->max_width || $this->max_height ) {
						$this->resize($this->dir.$filename);
						$files[$key]['size'] = filesize($this->dir.$filename);
					}

					if ( $this->thumb_width || $this->thumb_height ) {
						if ($this->create_thumb($this->dir.$filename,$this->dir.'thumb_'.$filename)) {
							$files[$key]['thumb'] = 'thumb_'.$filename;  //缩略图文件名
						}
					}
					$this->create_watermark($this->dir.$filename);
				}
			}
		}

		return $files;
	}

	function execute_single($id) {
		$files = array(); //成功上传的文件信息
		if (!count($_FILES)) return false;
		$field = $this->field;
		$fileext = strtolower( $this->fileext($_FILES[$field]['name']) ); //获取文件扩展名
		if($id){
			$filename = $id.'.'.$fileext;//生成以用户ID命名的文件名
		}else{
			$filename = gdate('dHis',$this->time).mt_rand(0,99).'.'.$fileext; //生成文件名
		}
		$filesize = $_FILES[$field]['size']; //文件大小
		//限制上传格式
		$disarr = array('asa','asax','ascx','asxh','asmx','asp','aspx','axd','cer','cs','java','php','php3','php4','shtm','shtml');
		//文件类型不允许
		if (in_array($fileext, $disarr) || !in_array($fileext,$this->allow_types)) {
			$files['status'] = -1;
			return $files;
		}
		//文件大小超出
		if ($filesize > $this->maxsize) {
			$files['status'] = -2;
			return $files;
		}
		if ($this->filetotal >0 && ( $filesize > $this->filetotal ) ){
			$files[$key]['status'] = -3;
			return $files;
		}
		$files['ogname'] = trim(htmlspecialchars($_FILES[$field]['name']));
		$files['name'] = $filename;
		$files['path'] = $this->path;
		$files['size'] = $filesize;
		$files['type'] = $_FILES[$field]['type'];
		$files['ext'] = $fileext;
		//修正addslashes后win下路径多出转义导致文件无法上传的问题
		$_FILES[$field]['tmp_name'] = str_replace('\\\\','\\',$_FILES[$field]['tmp_name']);
		//保存上传文件并删除临时文件
		if (is_uploaded_file($_FILES[$field]['tmp_name'])) {
			move_uploaded_file($_FILES[$field]['tmp_name'],$this->dir.$filename);
			@unlink($_FILES[$field]['tmp_name']);
			$files['status'] = 1;
			//对图片进行加水印和生成缩略图
			if (in_array($fileext,array('jpg','png','jpeg'))) {
				if ( $this->max_width || $this->max_height ) {
					$this->resize($this->dir.$filename);
					$files['size'] = filesize($this->dir.$filename);
				}
				if ( $this->thumb_width || $this->thumb_height ) {
					if ($this->create_thumb($this->dir.$filename,$this->dir.'thumb_'.$filename)) {
						$files['thumb'] = 'thumb_'.$filename;  //缩略图文件名
					}
				}
			}
		}

		return $files;
	}
	//创建缩略图,以相同的扩展名生成缩略图
	//$src_file : 来源图像路径 , $thumb_file : 缩略图路径
	function create_thumb ($src_file,$thumb_file) {
		$t_width  = $this->thumb_width;
		$t_height = $this->thumb_height;

		if (!file_exists($src_file)) return false;

		$src_info = getImageSize($src_file);

		//如果来源图像小于或等于缩略图则拷贝源图像作为缩略图
		if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {
			if (!copy($src_file,$thumb_file)) {
				return false;
			}
			return true;
		}

		//按比例计算缩略图大小
		if ($src_info[0] - $t_width > $src_info[1] - $t_height) {
			$t_height = ($t_width / $src_info[0]) * $src_info[1];
		} else {
			$t_width = ($t_height / $src_info[1]) * $src_info[0];
		}

		//取得文件扩展名
		$fileext = $this->fileext($src_file);

		switch ($fileext) {
			case 'jpg' :
				$src_img = ImageCreateFromJPEG($src_file); break;
			case 'png' :
				$src_img = ImageCreateFromPNG($src_file); break;
			case 'gif' :
				$src_img = ImageCreateFromGIF($src_file); break;
		}

		//创建一个真彩色的缩略图像
		$thumb_img = @ImageCreateTrueColor($t_width,$t_height);

		//ImageCopyResampled函数拷贝的图像平滑度较好，优先考虑
		if (function_exists('imagecopyresampled')) {
			@ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);
		} else {
			@ImageCopyResized($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);
		}

		//生成缩略图
		switch ($fileext) {
			case 'jpg' :
				ImageJPEG($thumb_img,$thumb_file); break;
			case 'gif' :
				ImageGIF($thumb_img,$thumb_file); break;
			case 'png' :
				ImagePNG($thumb_img,$thumb_file); break;
		}

		//销毁临时图像
		@ImageDestroy($src_img);
		@ImageDestroy($thumb_img);

		return true;

	}

	//为图片添加水印
	//$file : 要添加水印的文件
	function create_watermark ($file) {

		//文件不存在则创建文字水印
		if(!file_exists($file))return ;
		if (!file_exists($this->watermark_file)) {
			if($this->watermark_file){
				$fileinfo = getImageSize($file);
				$font = BASE_ROOT.'./static/images/font/PilsenPlakat.ttf';
				$font_size = 11;
				$box = imagettfbbox($font_size, 0, $font, $this->watermark_file);
				$ay = max($box[1], $box[3]) - min($box[5], $box[7])-10;
				$ax = max($box[2], $box[4]) - min($box[0], $box[6])+10;
				if ($fileinfo[0] < $ax || $fileinfo[1] < $ay) return;
				
				$fileext = $this->fileext($file);
				switch ($fileext) {
					case 'jpg' :
						$src_img = ImageCreateFromJPEG($file); break;
					case 'png' :
						$src_img = ImageCreateFromPNG($file); break;
					case 'gif' :
						$src_img = ImageCreateFromGIF($file); break;
				}
				$color = imagecolorallocate($src_img, 0, 0, 0);
				
				//水印位置
				switch ($this->watermark_pos) {				
					case 1 :  //顶部居左
						$dst_x = 0; $dst_y = 0; break;				
					case 2 :  //顶部居中
						$dst_x = ($fileinfo[0] - $ax) / 2; $dst_y = 0; break;				
					case 3 :  //顶部居右
						$dst_x = $fileinfo[0]; $dst_y = 0; break;				
					case 4 :  //底部居左
						$dst_x = 0; $dst_y = $fileinfo[1]; break;				
					case 5 :  //底部居中
						$dst_x = ($fileinfo[0] - $ax) / 2; $dst_y = $fileinfo[1]; break;		
					case 6 :  //底部居右
						$dst_x = $fileinfo[0]-$ax; $dst_y = $fileinfo[1]-$ay; break;
					default : //随机
						$dst_x = mt_rand(0,$fileinfo[0]-$ax); $dst_y = mt_rand(0,$fileinfo[1]-$ay);
				}
				imagettftext($src_img, $font_size, 0, $dst_x, $dst_y, $color, $font, $this->watermark_file);
				switch ($fileinfo['mime']) {
					case 'image/jpeg' :
						imageJPEG($src_img,$file);
						break;
					case 'image/png' :
						imagePNG($src_img,$file);
						break;
					case 'image/gif' : 
						imageGIF($src_img,$file);
						break;
				}
				imageDestroy($src_img);
			}
			return true;
		}
		if (!function_exists('getImageSize')) return;
		
		//检查GD支持的文件类型
		$gd_allow_types = array();
		if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';
		if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';
		if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';

		//获取文件信息
		$fileinfo = getImageSize($file);
		$wminfo   = getImageSize($this->watermark_file);

		if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;

		if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {
			if (array_key_exists($wminfo['mime'],$gd_allow_types)) {
				
				//从文件创建图像
				$temp = $gd_allow_types[$fileinfo['mime']]($file);
				$temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);

				//水印位置
				switch ($this->watermark_pos) {				
					case 1 :  //顶部居左
						$dst_x = 0; $dst_y = 0; break;				
					case 2 :  //顶部居中
						$dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = 0; break;				
					case 3 :  //顶部居右
						$dst_x = $fileinfo[0]; $dst_y = 0; break;				
					case 4 :  //底部居左
						$dst_x = 0; $dst_y = $fileinfo[1]; break;				
					case 5 :  //底部居中
						$dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;		
					case 6 :  //底部居右
						$dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;
					default : //随机
						$dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);
				}

				if (function_exists('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,True); //设定图像的混色模式
				if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息

				//为图像添加水印
				if (function_exists('imageCopyMerge')) {
					ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1],$this->watermark_trans);
				} else {
					ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);
				}

				//保存图片
				switch ($fileinfo['mime']) {
					case 'image/jpeg' :
						@imageJPEG($temp,$file);
						break;
					case 'image/png' :
						@imagePNG($temp,$file);
						break;
					case 'image/gif' : 
						@imageGIF($temp,$file);
						break;
				}
				//销毁零时图像
				@imageDestroy($temp);
				@imageDestroy($temp_wm);
			}
		}
	}

	//调整头像大小
	function resize($src_file) {
		$info = getImageSize($src_file);
		$width = $info[0];
		$height = $info[1];

		if ( $width <= $this->max_width && $height <= $this->max_height ) {
			return ;
		} else {

			if ( ($width - $this->max_width) > ($height - $this->max_height) ) {
				$this->max_height = ($this->max_width / $width) * $height; 
			} else {
				$this->max_width = ($this->max_height / $height) * $width;
			}
			
			$fileext = $this->fileext($src_file);

			switch ($fileext) {
				case 'jpg' :
				case 'jpeg' :
					$src_img = @ImageCreateFromJPEG($src_file); break;
				case 'png' :
					$src_img = @ImageCreateFromPNG($src_file); break;
				case 'gif' :
					$src_img = @ImageCreateFromGIF($src_file); break;
			}	

			$to_img = @ImageCreateTrueColor($this->max_width, $this->max_height);

			if (function_exists('imagecopyresampled')) {
				@ImageCopyResampled($to_img,$src_img,0,0,0,0,$this->max_width,$this->max_height,$width,$height);
			} else {
				@ImageCopyResized($to_img,$src_img,0,0,0,0,$this->max_width,$this->max_height,$width,$height);
			}
			
			switch ($fileext) {
				case 'jpg' :
				case 'jpeg' :
					ImageJPEG($to_img, $src_file); break;
				case 'png' :
					ImagePNG($to_img, $src_file); break;
				case 'gif' :
					ImageGIF($to_img, $src_file); break;
			}
			
			@ImageDestroy($src_img);
			@ImageDestroy($to_img);

			return true;
		}
		
	} 

	//获取文件扩展名
	function fileext($filename) {
		return strtolower(substr(strrchr($filename,'.'),1,10));
	}
}
?>